import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AgentLevelService } from '@core/routes-services/agent-level.service';
import { TRIGGER_TYPE, USER_ROLE_OPTION } from '../../../constant/dictionary';
import { TriggerService } from '@core/routes-services/trigger.service';
import { MarketFansService } from '@core/routes-services/market-fans.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { debounceTime, switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-trigger-edit',
  templateUrl: './trigger-edit.component.html',
})
export class TriggerEditComponent implements OnInit {
  triggerId: any;
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = true;

  triggerType: any[] = TRIGGER_TYPE;

  loadingOption: boolean = false;
  searchChange$ = new BehaviorSubject('');
  fansList: any [] = [];

  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private marketFansService: MarketFansService,
              private triggerService: TriggerService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    if (typeof this.entity.customerIds == 'string') {
      this.entity.customerIds = this.entity.customerIds ? JSON.parse(this.entity.customerIds) : null;
    }
    this.initValidForm();
    this.initCustomers();
  }

  initCustomers(){
    this.isLoading = true;
    if (this.entity.id) {
      this.marketFansService.getByIds(this.entity.id).then((res)=>{
        this.initSearchOption(res.data.content);
      },err=>{
        this.initSearchOption(null);
      })
    }else {
      this.initSearchOption(null);
      this.isLoading = false;
    }
  }

  initSearchOption(customerArr) {
    const searchFanOptions = (name: string) => this.marketFansService.searchOptions(name).then((res) => {
      if (res.status.toString().startsWith('20')) {
        return res.data.content;
        // this.page = res.data;
        // ++this.page.number;
      } else {
        this.message.warning(res.message);
        return [];
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      return [];
    });
    const optionList$: Observable<string[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(searchFanOptions));
    optionList$.subscribe(data => {
      console.log(data);
      this.fansList = data;

      if (customerArr) {
        for (const customer of customerArr) {
          if (this.fansList.findIndex((r) => r.id == customer.parentId) == -1) {
            this.fansList.push({ id: customer.id, name: customer.name });
          }
        }
      }
      this.loadingOption = false;
      this.isLoading = false;
    });
  }

  onSearch(value: string): void {
    this.loadingOption = true;
    this.searchChange$.next(value);
  }

  initValidForm() {
    this.entity.triggerType = this.entity.triggerType ? this.entity.triggerType : 1;
    this.entity.triggerDate = this.entity.triggerDate ? this.entity.triggerDate : 1;
    this.entity.beginTime = this.entity.beginTime ? new Date(this.entity.beginTime) : null;

    this.validateForm = this.fb.group({
      remark: [this.entity.remark, [Validators.required, Validators.maxLength(100)]],
      amount: [this.entity.amount, [Validators.required]],
      triggerCount: [this.entity.triggerCount, [Validators.required]],
      triggerType: [this.entity.triggerType, [Validators.required]],
      triggerDate: [this.entity.triggerDate, [Validators.required]],
      triggerTime: [this.entity.triggerTime, [Validators.required]],
      customerIds: [this.entity.customerIds, [Validators.required]],
      beginTime: [this.entity.beginTime, [Validators.required]],
    });
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.triggerService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
